package com.sakura.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.mapper.ProblemJudgeCaseMapper;
import com.sakura.oj.model.dto.judge.JudgeCaseAddRequest;
import com.sakura.oj.model.entity.ProblemJudgeCase;
import com.sakura.oj.service.ProblemJudgeCaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 题目用例服务类
 */
@Service
public class ProblemJudgeCaseServiceImpl extends ServiceImpl<ProblemJudgeCaseMapper, ProblemJudgeCase> implements ProblemJudgeCaseService {

    @Resource
    private ProblemJudgeCaseMapper judgeCaseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<JudgeCaseAddRequest> judgeCaseList, Long problemId) {
        if (CollUtil.isEmpty(judgeCaseList)) {
            return;
        }
        if (problemId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目id不能为空");
        }

        try {
            judgeCaseMapper.saveBatch(judgeCaseList, problemId);
        } catch (Exception e) {
            log.error("judge case saveBatch error", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "保存用例失败");
        }
    }

    @Override
    public HashMap<String, List<String>> getInputOutputList(Long problemId) {
        List<ProblemJudgeCase> judgeCases = this.list(new LambdaQueryWrapper<ProblemJudgeCase>().eq(ProblemJudgeCase::getProblemId, problemId));
        if (judgeCases.isEmpty()) {
            throw new RuntimeException("题目判题用例不存在");
        }
        HashMap<String, List<String>> map = new HashMap<>(2, 1.0f);
        map.put("input", judgeCases.stream().map(ProblemJudgeCase::getInput).toList());
        map.put("output", judgeCases.stream().map(ProblemJudgeCase::getOutput).toList());
        return map;
    }

    @Override
    public List<String> getInputList(Long problemId) {
        List<ProblemJudgeCase> judgeCases = this.list(new LambdaQueryWrapper<ProblemJudgeCase>().eq(ProblemJudgeCase::getProblemId, problemId));
        if (judgeCases.isEmpty()) {
            throw new RuntimeException("题目判题用例不存在");
        }
        return judgeCases.stream().map(ProblemJudgeCase::getInput).toList();
    }
}
